package web.demo.dao.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import web.demo.dao.IOrdersDao;
import web.demo.entity.Food;
import web.demo.entity.Orders;
import web.demo.utils.JdbcUtils;

public class OrdersDao implements IOrdersDao{

	@Override
	public boolean addOrders(web.demo.entity.Orders orders) {
		Object[] params={
				orders.getFoodTable_id(),
				orders.getOrder_date(),
				orders.getTotal_price(),
				orders.getStatus()
		};
		String sql="insert into orders (foodTable_id,order_date,total_price,status) values(?,?,?,?)";
		try {
			int result = JdbcUtils.getQueryRunner().update(sql,params);
			if(result>0){
				return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<web.demo.entity.Orders> getAll() {
		StringBuilder sb=new StringBuilder();
		sb.append(" select ");
		sb.append("   o.id, ");
		sb.append("   ft.id as foodTable_id, ");
		sb.append("   ft.name as foodTable_name, ");
		sb.append("   o.order_date, ");
		sb.append("   o.total_price, ");
		sb.append("   o.status ");
		sb.append(" from ");
		sb.append("   orders o ");
		sb.append("   inner join foodTable ft ");
		sb.append(" where 1=1 ");
		sb.append("   and o.foodTable_id=ft.id ");
		sb.append(" order by o.id desc ");
		
		try{
			return JdbcUtils.getQueryRunner().query(sb.toString(),new BeanListHandler<Orders>(Orders.class));
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean update(web.demo.entity.Orders orders) {
		String sql="update orders set foodTable_id=?,order_date=?,total_price=?,status=? where id=? ";
		Object[] params={
				orders.getFoodTable_id(),
				orders.getOrder_date(),
				orders.getTotal_price(),
				orders.getStatus(),
				orders.getId()
		};
		try {
			JdbcUtils.getQueryRunner().update(sql,params);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean delete(int ordersId) {
		//删除订单
		String sql="delete from orders where id=? ";
		try {
			int result = JdbcUtils.getQueryRunner().update(sql,ordersId);
			if(result>0){
				return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public Orders getByDate(Date date) {
		String sql="select * from orders where order_date=? ";
		try {
			return JdbcUtils.getQueryRunner().query(sql,new BeanHandler<Orders>(Orders.class),date);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
